package com.qczl.pme.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qczl.pme.dao.ChannelDao;
import com.qczl.pme.entity.PMEChannel;
import com.qczl.pme.service.ChannelService;
import com.qczl.pme.vo.ChannelVo;

/**
 * 栏目业务逻辑层实现类
 * 
 * @author SongR
 *
 */
@Service
public class ChannelServiceImpl implements ChannelService {
	Logger log = Logger.getLogger(this.getClass());

	@Autowired
	ChannelDao channeldao;

	/**
	 * 根据key获取栏目
	 */
	@Override
	public ChannelVo getByKey(String key) throws Exception {
		PMEChannel channel = channeldao.get("from PMEChannel where key='" + key + "' and status=0");
		if (null != channel) {
			ChannelVo vo = new ChannelVo();
			BeanUtils.copyProperties(channel, vo);
			return vo;
		}
		return null;
	}

	/**
	 * 编辑栏目
	 */
	@Override
	public void update(PMEChannel channel) throws Exception {
		PMEChannel c = channeldao.get("from PMEChannel where key='" + channel.getKey() + "' and status=0");
		c.setVisits(channel.getVisits());
		channeldao.update(c);
	}

	/**
	 * 实现获取顶级栏目
	 */
	@Override
	public List<ChannelVo> getTop(int start, int size) throws Exception {
		List<PMEChannel> channel = channeldao.findP("from PMEChannel where pid is null and status=0 order by sort",
				start, size);
		List<ChannelVo> vos = new ArrayList<ChannelVo>();
		for (PMEChannel c : channel) {
			ChannelVo vo = new ChannelVo();
			BeanUtils.copyProperties(c, vo);
			vos.add(vo);
		}
		return vos;
	}

	/**
	 * 实现获取顶级栏目数
	 */
	@Override
	public Long countTop() throws Exception {
		return channeldao.count("select count(*) from PMEChannel where pid is null and status=0");
	}

	/**
	 * 实现获取子级栏目
	 */
	@Override
	public List<ChannelVo> getChild(String key, int start, int size) throws Exception {
		PMEChannel channel = channeldao.get("from PMEChannel where key ='" + key + "'");
		List<ChannelVo> vos = new ArrayList<ChannelVo>();
		if (null != channel) {
			List<PMEChannel> channels = channeldao.findP(
					"from PMEChannel where pid =" + channel.getId() + " and status=0 order by sort", start, size);
			for (PMEChannel c : channels) {
				ChannelVo vo = new ChannelVo();
				BeanUtils.copyProperties(c, vo);
				vos.add(vo);
			}
		}
		return vos;
	}

	/**
	 * 实现获取子级栏目数
	 */
	@Override
	public Long countChild(String key) throws Exception {
		PMEChannel channel = channeldao.get("from PMEChannel where key ='" + key + "'");
		Long count = 0L;
		if (null != channel) {
			count = channeldao.count("select count(*) from PMEChannel where pid =" + channel.getId() + " and status=0");
		}

		return count;
	}

}
